<script setup>
import Codemirror from "codemirror-editor-vue3"
import "codemirror/mode/clike/clike"
import "codemirror/mode/javascript/javascript"
import { onMounted, onUnmounted, ref, watch } from 'vue'


const props = defineProps({
  isDrawerOpen: {
    type: Boolean,
    required: true,
  },
  operType: {
    type: Number,
    required: true,
    default: 0,
  },
  currRow: Object,
  currOption: Object,
})

const emit = defineEmits([
  'update:isDrawerOpen',
  'addData',
  'updateData',
])

const operType = ref(props.operType)
const currRow = ref(props.currRow)
const option = ref(props.currOption)
const row = currRow.value
const isFormValid = ref(false)
const refForm = ref()
const title = ref(operType.value == 0 ? '新增动态类':'更新动态类')

// 表单数据
const id = ref(row.id || '')
const classId = ref(row.classId || '')
const packagePath = ref(row.packagePath || '')
const className = ref(row.className || '')
const classLoaderType = ref(row.classLoaderType || 0)
const sourceCode = ref(row.sourceCode || '')
const sourceCodeTemplate = sourceCode.value
const classType = ref(row.classType || 0)
const isFallback = ref(row.isFallback || 0)
const version = ref(row.version || '')

const isFallbackShow = ref(false)

// 代码编辑器
const cmRef = ref()

const cmOptions = {
  // mode: "text/javascript"
  mode: "text/x-java",
}

const onChange = (val, cm) => {
  //console.log(val)
  //console.log(cm.getValue())
}

const onInput = val => {
  //console.log(val)
}

const onReady = cm => {
  //console.log(cm.focus())
}

onMounted(() => {
  // setTimeout(() => {
  //   cmRef.value?.refresh()
  // }, 1000)

  // setTimeout(() => {
  //   cmRef.value?.resize(100, 100)
  // }, 2000)

  // setTimeout(() => {
  //   cmRef.value?.cminstance.isClean()
  // }, 3000)

  checkClassType(classType.value)
})

onUnmounted(() => {
  cmRef.value?.destroy()
})

watch(classType, val => {
  checkClassType(val)
})

const checkClassType = val => {
  if(val != 0){
    isFallbackShow.value = true
  }else{
    isFallbackShow.value = false
    isFallback.value = 0
  }
}

// 👉 drawer close
const closeNavigationDrawer = () => {
  emit('update:isDrawerOpen', false)
  nextTick(() => {
    refForm.value?.reset()
    refForm.value?.resetValidation()
  })
}

const onSubmit = () => {
  refForm.value?.validate().then(({ valid }) => {
    if(valid) {
      const data = {
        id: id.value,
        classId: classId.value,
        packagePath: packagePath.value,
        className: className.value,
        classLoaderType: classLoaderType.value,
        sourceCode: sourceCode.value,
        classType: classType.value,
        isFallback: isFallback.value,
        version: version.value,
      }

      if(operType.value == 0){
        emit('addData', data)
      }else{
        emit('updateData', data)
      }
      
      emit('update:isDrawerOpen', false)
      nextTick(() => {
        refForm.value?.reset()
        refForm.value?.resetValidation()
      })
    }
  })
}

const handleDrawerModelValueUpdate = val => {
  emit('update:isDrawerOpen', val)
}

const codeTemplate = async () => {
  const res = await $ivyApi.post(API_URLS.lfDynamicClassCodeTemplate,{ 
    classType: classType.value,
    isFallback: isFallback.value,
  })
  sourceCode.value =  res.data
}

const revertTemplate = () => {
  sourceCode.value = sourceCodeTemplate
}
</script>

<template>
  <VNavigationDrawer
    temporary
    style="inline-size: 1120px;"
    location="end"
    class="scrollable-content"
    :model-value="props.isDrawerOpen"
    @update:model-value="handleDrawerModelValueUpdate"
  >
    <AppDrawerHeaderSection
      :title="title"
      @cancel="closeNavigationDrawer"
    />

    <!-- <PerfectScrollbar :options="{ wheelPropagation: false }"> -->
    <VCard
      flat
      style="overflow-y: auto;"
    >
      <VCardText>
        <VForm
          ref="refForm"
          v-model="isFormValid"
          @submit.prevent="onSubmit"
        >
          <VRow>
            <VCol
              v-if="false"
              cols="12"
            >
              <VTextField
                v-model="classId"
                class="setting-mb-12"
                label="类ID"
                clearable
              />
            </VCol>

            <VCol
              v-if="false"
              cols="12"
            >
              <VTextField
                v-model="packagePath"
                class="setting-mb-12"
                label="包路径"
                clearable
              />
            </VCol>

            <VCol cols="12">
              <VTextField
                v-model="className"
                :rules="[requiredValidator]"
                class="setting-mb-12"
                label="类名称"
                clearable
              />
            </VCol>

            <VCol cols="12">
              <VAutocomplete
                v-model="classLoaderType"
                label="加载器类型"
                :rules="[requiredValidator]"
                :items="option.classLoaderType.list"
                clearable
                item-title="title"
                item-value="value"
              />
            </VCol>

            <VCol cols="8">
              <VAutocomplete
                v-model="classType"
                label="class类型"
                :rules="[requiredValidator]"
                :items="option.classType.list"
                clearable
                item-title="title"
                item-value="value"
              />
            </VCol>
            <VCol cols="2">
              <VBtn
                class="w-100"
                @click="codeTemplate"
              >
                模板代码
              </VBtn>
            </VCol>
            <VCol cols="2">
              <VBtn
                class="w-100"
                @click="revertTemplate"
              >
                还原代码
              </VBtn>
            </VCol>

            <VCol
              v-if="isFallbackShow"
              cols="12"
            >
              <VRadioGroup
                v-model="isFallback"
                inline
              >
                <template #label>
                  <div>{{ option.isFallback.label }}</div>
                </template>
                <VRadio
                  v-for="(item,index) in option.isFallback.list"
                  :key="'isFallback'+index"
                  :label="item.title"
                  :value="item.value"
                  density="compact"
                />
              </VRadioGroup>
            </VCol>

            <VCol cols="12">
              <Codemirror
                ref="cmRef"
                v-model:value="sourceCode"
                :options="cmOptions"
                border
                height="300"
                width="100%"
                @change="onChange"
                @input="onInput"
                @ready="onReady"
              />
            </VCol>

            <VCol cols="6">
              <VBtn
                type="submit"
                class="me-3 w-100"
              >
                提交
              </VBtn>
            </VCol>
            <VCol cols="6">
              <VBtn
                class="w-100"
                type="reset"
                variant="tonal"
                color="secondary"
                @click="closeNavigationDrawer"
              >
                取消
              </VBtn>
            </VCol>
          </VRow>
        </VForm>
      </VCardText>
    </VCard>
    <!-- </PerfectScrollbar> -->
  </VNavigationDrawer>
</template>

<style scoped>
.w-100 {
  inline-size: 100%;
}
</style>
